package com.asit.controller;

import cn.hutool.json.JSONObject;
import com.asit.pojo.ReceiveMessage;
import com.asit.secure.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

@Controller
@Slf4j
public class SubController {
    @Autowired
    public SimpMessagingTemplate template;

    @GetMapping("/toIndex")
    public String toIndex(HttpServletRequest request, HttpServletResponse response) {
        // 跳转首页
        return "redirect:/index.html";
    }
    @GetMapping("/toTopic")
    public String toTopic() {
        return "redirect:/topic.html";
    }
    @GetMapping("/toQueue")
    public String toQueue() {
        return "redirect:/queue_test.html";
    }

    /**
     * 订阅
     * @return
     */
    @SubscribeMapping("/topic/getResponse")
    public String sub() {
        return "感谢您订阅了我";
    }

    /**
     * 为页面JS准备的调阅
     * @param param
     */
    @MessageMapping("/toTopicSendMsg")
    public void toTopicSendMsg(JSONObject param) {
        log.info("通过JS，从页面上接收到信息{}",param);
        //广播使用convertAndSend方法，第一个参数为目的地，和js中订阅的目的地要一致
        template.convertAndSend("/topic/getResponse", "参数："+param);
    }
    /**
     * 为页面JS准备的调阅
     * @param param
     */
    @MessageMapping("/sendMessage")
    public void sendMessage(JSONObject param, Principal principal) {
        log.info("---------queue2--------");
        String fromUser = principal.getName();
        String messageStr=fromUser+"发送了："+param;
        log.info(messageStr);
        SecurityUtil.getWebsocketSessionPool().forEach((key,val)->{
            log.info("当前在线人员为"+key);
            /*广播使用convertAndSendToUser方法，第一个参数为用户id，此时js中的订阅地址为
            "/user/" + 用户Id + "/message",其中"/user"是固定的*/
            template.convertAndSendToUser(key, "/getMessage", messageStr);
        });
    }
}